package study.cdc.debezium.support.keepalived;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.util.Random;


@Slf4j
public class HASwitcher {

    static String status = "ACTIVE";

    public static void registe() {
        try {
            String connectString = "150.158.122.249:2181";
            ZooKeeper zk = new ZooKeeper(connectString, 50000, null);
            String IP = "202.106.29.138";
            String port = new Random().nextInt(500) + "";
            if (zk.exists("/zk01", new MasterWatcher()) != null) { // 节点已经创建
                status = "STANDBY";
            } else {
                zk.create("/zk01", (IP + ":" + port).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
                status = "ACTIVE";
                log.info("启动active");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static class MasterWatcher implements Watcher {

        public void process(WatchedEvent event) {
            if (event.getType() == Event.EventType.NodeDeleted) {
                status = "ACTIVE";
                log.info("切换为active");
            }
        }
    }
}
